package com.example.juc.big_talk_concurrent.chapter3.article2;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

public class AtomicIntegerFieldUpdaterTest {

    /**
     * 入参 1 就是要更新字段所属的类，入参 2 就是要更新的字段。
     */
    private static AtomicIntegerFieldUpdater<User> updater = AtomicIntegerFieldUpdater.newUpdater(User.class, "age"); // 原子更新 User 类的 age 字段

    public static void main(String[] args) {
        User user = new User("user1", 1); // 旧值是 1
        int oldValue = updater.getAndAdd(user, 5); // 原子更新为 5
        System.out.println(oldValue); // 1
        System.out.println(updater.get(user)); // 6
    }

    static class User {
        private String userName;

        // 不能是private且需要volatile修饰
        public volatile int age;

        public User(String userName, int age) {
            this.userName = userName;
            this.age = age;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }
}

